package org.example.meetingsystem.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.meetingsystem.entity.CancellationRequest;
import org.example.meetingsystem.entity.Reservation;
import org.example.meetingsystem.enums.CancellationStatus;
import org.example.meetingsystem.enums.ReservationStatus;
import org.example.meetingsystem.mapper.CancellationRequestMapper;
import org.example.meetingsystem.mapper.ReservationMapper;
import org.example.meetingsystem.service.CancellationService;
import org.example.meetingsystem.util.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
@Transactional
public class CancellationServiceImpl implements CancellationService {

    private final CancellationRequestMapper cancellationRequestMapper;
    private final ReservationMapper reservationMapper;

    @Override
    @Transactional(readOnly = true)
    public List<CancellationRequest> getPendingRequests() {
        return cancellationRequestMapper.selectPendingRequests();
    }

    @Override
    public void processCancellationRequest(Long requestId, Boolean approved, Long processedBy) {
        log.info("处理取消申请: requestId={}, approved={}, processedBy={}", requestId, approved, processedBy);

        CancellationRequest request = cancellationRequestMapper.selectById(requestId);
        if (request == null) {
            throw new BusinessException("取消申请不存在");
        }

        if (request.getStatus() != CancellationStatus.PENDING) {
            throw new BusinessException("该申请已被处理");
        }

        // 更新申请状态
        request.setStatus(approved ? CancellationStatus.APPROVED : CancellationStatus.REJECTED);
        request.setProcessedBy(processedBy);
        request.setProcessedAt(LocalDateTime.now());

        int result = cancellationRequestMapper.updateById(request);
        if (result <= 0) {
            throw new BusinessException("更新申请状态失败");
        }

        // 如果批准，更新预订状态为已取消
        if (approved) {
            Reservation reservation = reservationMapper.selectById(request.getReservationId());
            if (reservation != null) {
                reservation.setStatus(ReservationStatus.CANCELLED);
                reservation.setUpdatedAt(LocalDateTime.now());

                int reservationResult = reservationMapper.updateById(reservation);
                if (reservationResult <= 0) {
                    throw new BusinessException("更新预订状态失败");
                }

                log.info("预订已取消: reservationId={}", reservation.getId());
            }
        }

        log.info("取消申请处理完成: requestId={}, status={}", requestId, request.getStatus());
    }

    @Override
    @Transactional(readOnly = true)
    public IPage<CancellationRequest> getCancellationRequests(Page<CancellationRequest> page, CancellationStatus status) {
        QueryWrapper<CancellationRequest> queryWrapper = new QueryWrapper<>();

        if (status != null) {
            queryWrapper.eq("status", status);
        }

        queryWrapper.orderByDesc("created_at");
        return cancellationRequestMapper.selectPage(page, queryWrapper);
    }

    @Override
    public Long createCancellationRequest(Long reservationId, String reason, Long requesterId) {
        log.info("创建取消申请: reservationId={}, requesterId={}", reservationId, requesterId);

        // 检查预订是否存在
        Reservation reservation = reservationMapper.selectById(reservationId);
        if (reservation == null) {
            throw new BusinessException("预订不存在");
        }

        //查看时间是否匹配
        if(reservation.getStartTime().minusHours(24).isBefore(LocalDateTime.now())){
            throw new BusinessException("订单不满足提前24小时申请，无法取消");
        }

        // 检查预订状态
        if (reservation.getStatus() == ReservationStatus.CANCELLED) {
            throw new BusinessException("预订已取消");
        }

        if (reservation.getStatus() == ReservationStatus.COMPLETED) {
            throw new BusinessException("已完成的预订无法取消");
        }

        // 检查是否已有待处理的取消申请
        QueryWrapper<CancellationRequest> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reservation_id", reservationId)
                .eq("status", CancellationStatus.PENDING);

        CancellationRequest existingRequest = cancellationRequestMapper.selectOne(queryWrapper);
        if (existingRequest != null) {
            throw new BusinessException("该预订已有待处理的取消申请");
        }

        // 创建取消申请
        CancellationRequest request = new CancellationRequest();
        if(reservation.getStartTime().minusHours(72).isAfter(LocalDateTime.now())){
            request.setRefundRate(BigDecimal.ONE);
        }else if(reservation.getStartTime().minusHours(48).isAfter(LocalDateTime.now())){
            request.setRefundRate(BigDecimal.valueOf(0.75));
        }else if(reservation.getStartTime().minusHours(24).isAfter(LocalDateTime.now())){
            request.setRefundRate(BigDecimal.valueOf(0.25));
        }

        request.setRefundRate(BigDecimal.valueOf(1));
        request.setRefundAmount(reservation.getTotalAmount());
        request.setCustomerId(reservation.getCustomerId());
        request.setReservationId(reservationId);
        request.setReason(reason);
        request.setStatus(CancellationStatus.PENDING);
        request.setCreatedAt(LocalDateTime.now());

        int result = cancellationRequestMapper.insert(request);
        if (result <= 0) {
            throw new BusinessException("创建取消申请失败");
        }

        log.info("取消申请创建成功: requestId={}", request.getId());
        return request.getId();
    }

    @Override
    @Transactional(readOnly = true)
    public CancellationRequest getCancellationRequestById(Long id) {
        return cancellationRequestMapper.selectById(id);
    }
}
